package com.xiaolei.openokjoke.Adapters;

import android.content.Context;
import android.util.AttributeSet;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


/**
 * Created by zhuxuyang on 17/1/4.
 */

public class LoadMoreRecyclerView extends RecyclerView {
    public LoadMoreRecyclerView(Context context) {
        super(context);
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        if (!(adapter instanceof RecyclerBaseAdapter)) {
            throw new ClassCastException("not a RecyclerBaseAdapter.");
        }
        super.setAdapter(adapter);

        setLoadMore();
    }

    @Override
    public void setLayoutManager(LayoutManager layout) {
        if (!(layout instanceof LinearLayoutManager)) {
            throw new ClassCastException("not a LinearLayoutManager.");
        }

        super.setLayoutManager(layout);
    }

    private void setLoadMore() {
        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (((RecyclerBaseAdapter) getAdapter()).hasLoadMore()) {
                        boolean isLast = ((RecyclerBaseAdapter) getAdapter()).getDataSize() == ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
                        if (isLast && ((RecyclerBaseAdapter) getAdapter()).getOnLoadMoreListener() != null) {
                            ((RecyclerBaseAdapter) getAdapter()).getOnLoadMoreListener().loadMore();
                        }
                    }
                }
            }
        });
    }

}
